package com.cy.study.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.study.common.BasePageReq;
import com.cy.study.entity.AdminInfoEntity;
import com.cy.study.entity.NewsEntity;
import com.cy.study.entity.PushRecordEntity;
import com.cy.study.exception.BusinessException;
import com.cy.study.mapper.AdminInfoMapper;
import com.cy.study.mapper.NewsMapper;
import com.cy.study.mapper.PushRecordMapper;
import com.cy.study.req.NewsAddReq;
import com.cy.study.req.DeleteNewsReq;
import com.cy.study.req.NewsPageReq;
import com.cy.study.req.NewsUpdateReq;
import com.cy.study.res.NewsDetailRes;
import com.cy.study.res.NewsPageRes;
import com.cy.study.res.PushGetNewsRes;
import com.cy.study.service.NewsService;
import com.cy.study.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class NewsServiceImpl extends ServiceImpl<NewsMapper, NewsEntity> implements NewsService {

    private final AdminInfoMapper adminInfoMapper;
    private final NewsMapper newsMapper;

    private final PushRecordMapper pushRecordMapper;


    @Override
    public Integer addNews(NewsAddReq req) {
        NewsEntity news = new NewsEntity();
        Integer userId = SecurityUtils.getUserId();
        news.setTitle(req.getTitle());
        news.setBody(req.getBody());
        news.setAdminId(userId);
        news.setCreateTime(LocalDateTime.now());
        this.getBaseMapper().insert(news);
        return news.getId();
    }

    @Override
    public void deleteNews(DeleteNewsReq req) {
        //有推送记录的不能删除
        Integer newsId = req.getId();
        QueryWrapper<PushRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PushRecordEntity::getRelationId,newsId);
        Long count = pushRecordMapper.selectCount(wrapper);
        if(count!=0){
            throw new BusinessException("该资讯已有推送，不允许删除");
        }
        this.removeById(req.getId());
    }

    @Override
    public Page<NewsPageRes> pageNews(NewsPageReq req) {
        Page page = new Page(req.getPageNum(), req.getPageSize());
        Page<NewsPageRes> res = this.getBaseMapper().pageNews(req,page);
        return res;
    }

    @Override
    public NewsDetailRes detail(Integer newsId) {
        NewsEntity newsEntity = this.getBaseMapper().selectById(newsId);
        NewsDetailRes res = new NewsDetailRes();
        BeanUtils.copyProperties(newsEntity,res);
        AdminInfoEntity adminInfoEntity = adminInfoMapper.selectById(newsEntity.getAdminId());
        res.setAdminName(adminInfoEntity==null?"默认管理员":adminInfoEntity.getName());
        return res;
    }

    @Override
    public Page<NewsEntity> userList(BasePageReq req) {
        Page page = new Page(req.getPageNum(),req.getPageSize());
        QueryWrapper<NewsEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(NewsEntity::getCreateTime);
        Page news = this.getBaseMapper().selectPage(page,wrapper);
        List<NewsEntity> records = news.getRecords();
        List<NewsDetailRes> res = new ArrayList<>();
        records.stream().forEach(e->{
            NewsDetailRes temp = new NewsDetailRes();
            BeanUtils.copyProperties(e,temp);
            AdminInfoEntity adminInfoEntity = adminInfoMapper.selectById(e.getAdminId());
            temp.setAdminName(adminInfoEntity==null?"默认管理员":adminInfoEntity.getName());
            res.add(temp);
        });
        news.setRecords(res);
        return news;
    }

    @Override
    public List<PushGetNewsRes> pushGetNews() {
        LocalDate now = LocalDate.now();
        LocalDateTime start = now.plusDays(-90).atStartOfDay();
        LocalDateTime end = now.plusDays(1).atStartOfDay().plusSeconds(-1);
        QueryWrapper<NewsEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().between(NewsEntity::getCreateTime,start,end)
                .orderByDesc(NewsEntity::getCreateTime);
        List<NewsEntity> list = newsMapper.selectList(wrapper);
        List<PushGetNewsRes> res = new ArrayList<>(list.size());
        list.stream().forEach(e->{
            PushGetNewsRes temp = new PushGetNewsRes();
            temp.setId(e.getId());
            temp.setTitle(e.getTitle());
            res.add(temp);
        });
        return res;
    }

    @Override
    public void updateNews(NewsUpdateReq req) {
        if(req.getId()==null){
            throw new BusinessException("id不能为空");
        }
        if(req.getTitle()==null || StrUtil.isBlank(req.getTitle())){
            throw new BusinessException("标题不能为空");
        }
        if(req.getBody()==null || StrUtil.isBlank(req.getBody())){
            throw new BusinessException("内容不能为空");
        }
        NewsEntity news = newsMapper.selectById(req.getId());
        if(news==null){
            throw new BusinessException("资讯为空，请确认资讯id");
        }
        news.setTitle(req.getTitle());
        news.setBody(req.getBody());
        newsMapper.updateById(news);
    }
}
